package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.service.CourseCategoryService;
import com.xuecheng.domain.dto.CourseCategoryTreeDto;
import com.xuecheng.domain.po.CourseCategory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Resource
    private CourseCategoryMapper courseCategoryMapper;



    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //获取所有叶子节点
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //定义一个List集合，用来存放最终的树形结构
        List<CourseCategoryTreeDto> result = new ArrayList<>();
        //将查询到的所有叶子节点转成map，过滤掉当前id的节点，剩下的就是父节点与叶子节点
        Map<String, CourseCategoryTreeDto> collect = courseCategoryTreeDtos.stream().filter(item ->!id.equals(item.getId())).collect(Collectors.toMap(CourseCategory::getId, value -> value, (key1, key2) -> key2));
        //将所有叶子节点从头遍历，进行分类，组装成树形结构 能查到父节点等于传入当前id的作为根节点，否则作为子节点
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item -> {
            if (item.getParentid().equals(id)){
                //组装1级节点，直接添加到最终结果中
                result.add(item);
            }
            //将map中的节点取出，判断父id是否等于当前节点的parentid，如果是则作为子节点添加到父节点中
            CourseCategoryTreeDto treeDto = collect.get(item.getParentid());
            if (treeDto!=null){
                if (treeDto.getChildrenTreeNodes()==null) {
                    treeDto.setChildrenTreeNodes(new ArrayList<>());
                }
                treeDto.getChildrenTreeNodes().add(item);
            }

        });
        return result;
    }
}
